package com.lanou.bookstore.cart.web.servlet;

import com.lanou.bookstore.book.domain.Book;
import com.lanou.bookstore.book.service.BookService;
import com.lanou.bookstore.cart.domain.Cart;
import com.lanou.bookstore.cart.domain.CartItem;
import com.lanou.bookstore.util.BaseServlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet(name = "CartServlet", urlPatterns = "/cart.do")
public class CartServlet extends BaseServlet {

    private BookService bookService = new BookService();

    private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String bid = req.getParameter("bid");
        String count = req.getParameter("count");

        Cart cart = (Cart) req.getSession().getAttribute("cart");
        Book book = bookService.load(bid);//获取图书信息
        CartItem cartItem = new CartItem();
        cartItem.setBook(book)
                .setCount(Integer.valueOf(count));
        List cartItems = cart.getItems();
        cartItems.add(cartItem);

    }

    private void del(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String bid = req.getParameter("bid");
        HttpSession session = req.getSession();
        Cart cart = (Cart) session.getAttribute("items");
        cart.delItem(bid);
        resp.sendRedirect("/jsps/cart/list.jsp");


    }

    private void clear(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        HttpSession session = req.getSession();
        Cart cart = (Cart) session.getAttribute("items");
        cart.clearItems();
        resp.sendRedirect("/jsps/cart/list.jsp");
    }
}
